package com.atlzk.common.utils;

import redis.clients.jedis.Jedis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtils {
    public static byte[] serialize(Object obj){
        byte[] bytes = null;
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();;
            ObjectOutputStream oos=new ObjectOutputStream(baos);
            oos.writeObject(obj);
            bytes=baos.toByteArray();
            baos.close();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
    public static Object deSerialize(byte[] bytes){
        Object obj=null;
        try {
            ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
            ObjectInputStream ois=new ObjectInputStream(bais);
            obj=ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }


    //============使用案例============
/*    OrderEntity orderEntity_new = null;
    //连接本地redis
    Jedis jedis = new Jedis("localhost", 6379);
    byte[] bytes = jedis.get(("kanOrder" + orderEntity.getOmsOrderId()).getBytes());
    //判断redis 中是否存在
        if (bytes == null) {
        //redis中不存在  查询最新记录 存入redis
        orderEntity_new = orderDao.selectById(orderEntity.getOmsOrderId());
        byte[] kanOrder_serialize = SerializeUtils.serialize(orderEntity_new);
//            setex有3个参数：第1个是String类型的key，第2个是int类型的过期 秒数 (单位、秒)，第3个是key对应的value。
        jedis.setex(("kanOrder" + orderEntity_new.getOmsOrderId()).getBytes(),100, kanOrder_serialize);
    }else {
        //redis中存在  直接反序列化获取
        orderEntity_new =(OrderEntity) SerializeUtils.deSerialize(bytes);
    }
        System.out.println(orderEntity_new.toString());*/

    }